﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDatagrid.Models;
using System.IO;
using Helpers;
using ImageResizer;

namespace MvcDatagrid.Controllers
{
    public class PicturesController : Controller
    {
        private IPicturesRepository _picturesRepository;

        public PicturesController(IPicturesRepository pictureRepository)
        {
            _picturesRepository = pictureRepository;
        }

        public ActionResult KODisplayPictures()
        {
            return View(_picturesRepository.GetAllPictures());
        }
        public ActionResult DeleteImage(FormCollection postedFormData)
        {
            string pictureId = postedFormData["pictureID"];
            Images imgToDelete = _picturesRepository.GetPictureById(Int32.Parse(pictureId));
            string status = string.Empty;
            try
            {
                _picturesRepository.DeletePicture(imgToDelete);
                status = "succeed";
            }
            catch(Exception ex){
                status = "failed";
            }
            return Json(new
            {
                Status = status
            });
        }

        public ActionResult UpdatePictureInformation(FormCollection postedFormData)
        {
            string pictureId = postedFormData["pictureID"];
            Images img = _picturesRepository.GetPictureById(Convert.ToInt32(pictureId));
            img.Title = Convert.ToString(postedFormData["pictureTitle"]);
            string status = string.Empty;
            try
            {
                _picturesRepository.UpdatePicture(img);
                status = "succeed";
            }
            catch (Exception ex)
            {
                status = string.Format("Failed \n{0}", ex.ToString());
            }
            System.Threading.Thread.Sleep(2000);
            return Json(new
            {
                Status = status,
                Title = img.Title
            });
        }
        //
        // GET: /Pictures/
        public ActionResult Index()
        {
            return View(_picturesRepository.GetAllPictures());
        }


        private dynamic UploadFile(HttpPostedFileBase file)
        {
            var absPath = @"/uploads/img";
            var absFileAndPath = string.Format("{0}/{1}", absPath, file.FileName);
            
            string dest = Server.MapPath(absFileAndPath);
            
            file.SaveAs(dest);

            Images img = new Images();
            img.Title = file.FileName;
            img.ImgPath = string.Format("{0}/{1}", absPath,file.FileName);
            _picturesRepository.AddPicture(img);

            return new { path = img.ImgPath, name = file.FileName, view = Helpers.HtmlHelperExtensions.RenderPartialView(this, "picture", img) };
        }

        private dynamic UploadThumbnail(HttpPostedFileBase file)
        {
            var absPath = @"/uploads/img";
            var absFileAndPath = string.Format(@"~{0}/{1}", absPath, file.FileName);
            int width = 150;
            int height = 100;
            var resizeSettings = new ImageResizer.ResizeSettings
            {
                Scale = ImageResizer.ScaleMode.DownscaleOnly,
                Width = width,
                Height = height,
            };
            //ImageJob i = new ImageJob(file, absFileAndPath, resizeSettings);
            ImageJob i = new ImageJob(file, absFileAndPath, new ResizeSettings("width=200;height=150;format=jpg"));
            // Save resized picture
            i.Build();
            
            // Save actual¨picture
            //file.SaveAs(i.FinalPath);

            Images img = new Images();
            img.Title = file.FileName;
            img.ImgPath = string.Format("{0}/{1}", absPath, file.FileName);
            _picturesRepository.AddPicture(img);

            return new { path = img.ImgPath, name = file.FileName, view = Helpers.HtmlHelperExtensions.RenderPartialView(this, "picture", img) };
        }
        [HttpPost]
        public ActionResult UploadManyFilesAction()
        {
            if (Request.Files.Count == 0)
            {
                return Json(new { statusCode = 500, status = "No image provided." }, "text/html");
            }
            try
            {
                var file = Request.Files[0];
                var res = UploadThumbnail(file);
                return Json(new
                {
                    statusCode = 200,
                    status = "Image uploaded.",
                    file = res.name,
                    path = res.path,
                    view = res.view
                }, "text/html");
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    statusCode = 500,
                    status = "Error uploading image.",
                    file = string.Empty
                }, "text/html");
            }
        }
    }
}
